package com.example.demo.sys.common;

import org.apache.commons.collections.map.LinkedMap;
import org.apache.shiro.util.CollectionUtils;

import javax.validation.*;
import java.util.*;

/**
 * Created by 蔡超 on 2018/10/6.
 */
public class BeanValidator {
    private static ValidatorFactory validatorFactory = Validation.buildDefaultValidatorFactory();

    /** 
    * @Description: 验证一个对象
    * @Param:  
    * @return:  
    * @Author: 蔡超
    * @Date: 2018/10/6 10:43
    */
    public static <T> Map<String,String> validate(T t,Class... groups){
        Validator validator = validatorFactory.getValidator();
        Set validateResult = validator.validate(t,groups);
        if(validateResult.isEmpty()){
            return Collections.emptyMap();
        }else {
            LinkedHashMap<String,String> linkedHashMap = new LinkedHashMap<String,String>();
            Iterator iterator = validateResult.iterator();
            while (iterator.hasNext()){
                ConstraintViolation constraintViolation = (ConstraintViolation) iterator.next();
                linkedHashMap.put(constraintViolation.getPropertyPath().toString(),constraintViolation.getMessage());
            }
            return  linkedHashMap;
        }
    }

    /** 
    * @Description: 验证一个集合
    * @Param:  
    * @return:  
    * @Author: 蔡超
    * @Date: 2018/10/6 10:43
    */
    public static Map<String,String> validateList(Collection collection){
        if(!CollectionUtils.isEmpty(collection)){
            Iterator iterator = collection.iterator();
            Map map = new LinkedMap();
            do {
                if(iterator.hasNext()){
                    Object object = iterator.next();
                    map.put(object,new Class[0]);
                }
            }while (map.isEmpty());
            return map;
        }else{
            return Collections.emptyMap();
        }
    }

    public static Map<String,String> validateObject(Object first,Object... objects){
        if(objects !=null && objects.length > 0){
            return validateList(Arrays.asList(first,objects));
        }else{
            return validate(first,new Class[0]);
        }
    }

}
